package com.qiantu.phone.ui.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.hjq.widget.layout.SettingBar;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.LinkageBean;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.bean.LocationData;
import com.qiantu.phone.ui.activity.map.LocationActivity;
import com.qiantu.phone.utils.LinkageDataHolder;
import com.qiantu.phone.widget.StatusSeekBar;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * time   : 2021/12/22
 */
public final class TemperatureActivity extends AppActivity {

    private SettingBar settingReferenceArea;
    private SettingBar settingDataSourceDevice;
    private TextView tvTemperatureCondition;
    private RadioGroup whenRadioGroup;
    private StatusSeekBar temperatureSeekBar;
    //1小于、2等于、3大于
    private int logicType = 1;
    private String logicTypeStr;
    private int temperature = 25;
    private String unit = "℃";
    //是否时室内
    private boolean isIndoor;
    private String deviceSerialNo;
    private String serialNo;
    private String areaName;
    private String areaCoding;
    private String deviceName;
    private double latitude;
    private double longitude;
    private int scopeLong;
    private LinkageBean mLinkageBean;
    private LinkageBean.LinkageCondition mLinkageCondition;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_temperature;
    }

    @Override
    protected void initView() {
        settingReferenceArea = findViewById(R.id.setting_reference_area);
        settingDataSourceDevice = findViewById(R.id.setting_data_source_device);
        tvTemperatureCondition = findViewById(R.id.tv_temperature_condition);
        whenRadioGroup = findViewById(R.id.when_radio_group);
        temperatureSeekBar = findViewById(R.id.temperature_seek_bar);
        whenRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.type_less_than:
                        logicType = 1;
                        logicTypeStr = getString(R.string.less_than);
                        break;
                    case R.id.type_equal_to:
                        logicType = 2;
                        logicTypeStr = getString(R.string.equal_to);
                        break;
                    case R.id.type_greater_than:
                        logicType = 3;
                        logicTypeStr = getString(R.string.greater_than);
                        break;
                }
                tvTemperatureCondition.setText(getString(R.string.effective_when_time_holder, logicTypeStr + temperature + unit));
            }
        });
        temperatureSeekBar.setOnSeekBarChangeListener(new StatusSeekBar.OnSeekBarChangeListener() {
            @Override
            public void onValueChanged(int value) {
                if (temperature == value) {
                    return;
                }
                temperature = value;
                tvTemperatureCondition.setText(getString(R.string.effective_when_time_holder, logicTypeStr + temperature + unit));
            }

            @Override
            public void onStartTrackingTouch() {

            }

            @Override
            public void onStopTrackingTouch(int value) {
                if (temperature == value) {
                    return;
                }
                temperature = value;
                tvTemperatureCondition.setText(getString(R.string.effective_when_time_holder, logicTypeStr + temperature + unit));
            }
        });
    }

    @Override
    protected void initData() {
        isIndoor = getBoolean("is_indoor");
        serialNo = getString("serial_no");
        deviceSerialNo = getString("device_serial_no");
        areaCoding = getString("room_serial_no");
        areaName = getString("floor_room_name");
        deviceName = getString("device_name");
        mLinkageBean = LinkageDataHolder.getLinkageData();
        if (mLinkageBean != null) {
            List<LinkageBean.LinkageCondition> linkageConditions = mLinkageBean.getLinkageConditions();
            if (linkageConditions != null && linkageConditions.size() > 0 && !TextUtils.isEmpty(serialNo)) {
                for (LinkageBean.LinkageCondition item : linkageConditions) {
                    if (item.getConditionSerialNo().equals(serialNo)) {
                        mLinkageCondition = item;
                        isIndoor = mLinkageCondition.getAreaType() == 1 ? true : false;
                        if (isIndoor) {
                            deviceSerialNo = mLinkageCondition.getDeviceSerialNo();
                            deviceName = LLDeviceDBManager.getInstance(TemperatureActivity.this).get(deviceSerialNo).getName();
                        }
                        areaName = mLinkageCondition.getAreaName();
                        areaCoding = mLinkageCondition.getAreaCoding();
                        logicType = mLinkageCondition.getLogicType();
                        temperature = mLinkageCondition.getBeginValue();
                        latitude = mLinkageCondition.getLatitude();
                        longitude = mLinkageCondition.getLongitude();
                        scopeLong = mLinkageCondition.getScopeLong();
                        break;
                    }
                }
            }
        }
        updateView();
    }

    private void updateView() {
        if (isIndoor) {
            setTitle(R.string.indoor_temperature);
            settingReferenceArea.setEnabled(false);
            settingReferenceArea.setRightDrawable(null);
            settingDataSourceDevice.setVisibility(View.VISIBLE);
            settingDataSourceDevice.setRightText(deviceName);
            setOnClickListener(settingDataSourceDevice);
            List<DeviceBean> data = LLDeviceDBManager.getInstance(getContext()).getRoomEnvironmentDevices(areaCoding, DeviceBean.ENVIRONMENT_TYPE_TEMPERATURE);
            if(data.size() > 1){
                settingDataSourceDevice.setRightDrawable(AppApplication.getInstance().getThemeDrawable(R.attr.icon_list_next_normal));
                settingDataSourceDevice.setEnabled(true);
            }else{
                settingDataSourceDevice.setRightDrawable(null);
                settingDataSourceDevice.setEnabled(false);
            }
        } else {
            setTitle(R.string.outdoor_temperature);
            settingReferenceArea.setRightDrawable(AppApplication.getInstance().getThemeDrawable(R.attr.icon_list_next_normal));
            if(TextUtils.isEmpty(areaName)){
                longitude = AppApplication.getInstance().getCurHouseInfo().getLongitude();
                latitude = AppApplication.getInstance().getCurHouseInfo().getLatitude();
                scopeLong = AppApplication.getInstance().getCurHouseInfo().getRange();
                areaName = AppApplication.getInstance().getCurHouseInfo().getProvince() + " " + AppApplication.getInstance().getCurHouseInfo().getCity() + " " + AppApplication.getInstance().getCurHouseInfo().getDistrict();
                areaCoding = AppApplication.getInstance().getCurHouseInfo().getDistrictId();
            }
            setOnClickListener(settingReferenceArea);
            settingDataSourceDevice.setVisibility(View.GONE);
        }
        settingReferenceArea.setRightText(areaName);
        switch (logicType) {
            case 1:
                ((RadioButton) whenRadioGroup.getChildAt(0)).setChecked(true);
                break;
            case 2:
                ((RadioButton) whenRadioGroup.getChildAt(2)).setChecked(true);
                break;
            case 3:
                ((RadioButton) whenRadioGroup.getChildAt(4)).setChecked(true);
                break;
        }
        temperatureSeekBar.setValue(temperature);
    }

    @Override
    public void onRightClick(View view) {
        if (TextUtils.isEmpty(areaName)) {
            toast(R.string.please_select_reference_area_hint);
            return;
        }
        //当前联动空，才去
        if (mLinkageCondition == null) {
            //本地保存联动条件
            if (mLinkageBean == null) {
                mLinkageBean = new LinkageBean();
                LinkageDataHolder.setLinkageData(mLinkageBean);
            }
            List<LinkageBean.LinkageCondition> linkageConditions = mLinkageBean.getLinkageConditions();
            if (linkageConditions == null) {
                linkageConditions = new ArrayList<>();
            }
            mLinkageBean.setLinkageConditions(linkageConditions);
            mLinkageCondition = new LinkageBean.LinkageCondition();
            //先设置个本地的SerialNo，为了编辑找到对应的数据
            mLinkageCondition.setConditionSerialNo(UUID.randomUUID().toString());
            mLinkageCondition.setConditionType(2);
            linkageConditions.add(mLinkageCondition);
            mLinkageCondition.setSort(linkageConditions.indexOf(mLinkageCondition) + 1);
        }
        if (isIndoor) {
            mLinkageCondition.setAreaType(1);
            mLinkageCondition.setDeviceSerialNo(deviceSerialNo);
        } else {
            mLinkageCondition.setAreaType(2);
            mLinkageCondition.setLongitude(longitude);
            mLinkageCondition.setLatitude(latitude);
            mLinkageCondition.setScopeLong(scopeLong);
        }
        mLinkageCondition.setAreaName(areaName);
        mLinkageCondition.setAreaCoding(areaCoding);
        mLinkageCondition.setBeginValue(temperature);
        mLinkageCondition.setEndValue(temperature);
        mLinkageCondition.setLogicType(logicType);
        mLinkageCondition.setImageUrl("icon_intelligent_environment_temperature");
        mLinkageCondition.setBriefing("温度");
        mLinkageCondition.setStateName("temperature");
        startActivity_SingleTask(EditLinkageActivity.class);
        finish();
    }

    @Override
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.setting_reference_area:
//                showBottomDistrictDialog();
                intent = new Intent(getContext(), LocationActivity.class);
                LocationData locationData = new LocationData();
                if(longitude > 0 && latitude > 0){
                    locationData.location = longitude + ":" + latitude;
                    locationData.scopeLong = scopeLong;
                }else{
                    if (AppApplication.getInstance().getCurHouseInfo() != null) {
                        locationData.location = AppApplication.getInstance().getCurHouseInfo().getLongitude() + ":" + AppApplication.getInstance().getCurHouseInfo().getLatitude();
                    }
                }
                LocationActivity.startForResult(this, locationData, 1, LocationActivity.LOCATION_REQUEST_CODE);
                break;
            case R.id.setting_data_source_device:
                intent = new Intent(this, DataSourceDeviceActivity.class);
                intent.putExtra("device_serial_no", deviceSerialNo);
                intent.putExtra("room_serial_no", areaCoding);
                intent.putExtra("environment_type", DeviceBean.ENVIRONMENT_TYPE_TEMPERATURE);
                startActivityForResult(intent, new OnActivityCallback() {
                    @Override
                    public void onActivityResult(int resultCode, @Nullable Intent data) {
                        if(resultCode == RESULT_OK){
                            areaName = data.getStringExtra("floor_room_name");
                            areaCoding = data.getStringExtra("room_serial_no");
                            deviceName = data.getStringExtra("device_name");
                            deviceSerialNo = data.getStringExtra("device_serial_no");
                            settingReferenceArea.setRightText(areaName);
                            settingDataSourceDevice.setRightText(deviceName);
                        }
                    }
                });
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            if (requestCode == LocationActivity.LOCATION_REQUEST_CODE) {
                LocationData locationData = (LocationData) data.getSerializableExtra("DATA");
                longitude = locationData.longitude;
                latitude = locationData.latitude;
                scopeLong = locationData.scopeLong;
                areaName = locationData.province + " " + locationData.city + " " + locationData.district;
                areaCoding = locationData.provinceId + locationData.cityId + locationData.districtId;
                settingReferenceArea.setRightText(areaName);
            }
        }
    }

//    private BottomDistrictDialog mBottomDistrictDialog;
//
//    private void showBottomDistrictDialog() {
//        if (mBottomDistrictDialog == null) {
//            mBottomDistrictDialog = new BottomDistrictDialog(this);
//            mBottomDistrictDialog.setDialogClickListener(new BottomDistrictDialog.DialogClickListener() {
//                @Override
//                public void onConfirmClick(String text, String code) {
//                    areaName = text;
//                    areaCoding = code;
//                    settingReferenceArea.setRightText(areaName);
//                    mBottomDistrictDialog.dismiss();
//                }
//            });
//            new XPopup.Builder(this)
//                    .dismissOnBackPressed(true)
//                    .enableDrag(true)
//                    .asCustom(mBottomDistrictDialog);
//        }
//        mBottomDistrictDialog.show();
//    }
}